// dir_model_holder.js

import GetterJS from './getter'



function copyObjectFields(src, dst) {
    if ((src == null) || (dst == null)) { return }
    for (let key in src) {
        let val = src[key]
        dst[key] = val
    }
}


////////////////////////////////////////////////////////////////////////////////

// ItemFacade is the Item-Holder
function ItemFacade(item, parent) {
    this.item = item
    this.parent = parent
}

ItemFacade.prototype = {

    GetAt() {
        let src = this.item.at
        let str = JSON.stringify(src)
        let dst = JSON.parse(str)
        if (dst.path == null) {
            dst.path = []
        }
        return dst
    },

    GetName() {
        let name = this.item.name;
        if (name == null) { name = "" }
        return name
    },

}

////////////////////////////////////////////////////////////////////////////////

// Holder is the Model-Holder
function Holder(model) {
    if (model == null) { model = {} }
    this.model = model;
}

Holder.prototype = {

    GetItems() {
        let list = this.model.items;
        if (list == null) { list = [] }
        return list;
    },

    GetItem(name) {
        let list = this.GetItems();
        let item = {}
        for (let i in list) {
            let item1 = list[i]
            if (item1.name == name) {
                item = item1
                break
            }
        }
        return new ItemFacade(item, this)
    },

    Export() {
        let src = this.model;
        let dst = {}
        copyObjectFields(src, dst)
        return dst
    },

    Import(src) {
        let dst = this.model;
        copyObjectFields(src, dst)
        return dst
    },

    GetURI() {
        let g = GetterJS.NewGetter(this.model);
        return g.Get('uri', '.', "uri:none")
    },

}

function createNewHolder(model) {
    return new Holder(model)
}

////////////////////////////////////////////////////////////////////////////////

export default {
    name: "dir-model-holder",
    NewHolder: createNewHolder,
}
